<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use \think\Log;
/**
 * 模型数据管理控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class SuController extends AdminController {

    /**
     * 显示指定模型列表数据
     * @param  String $model 模型标识
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function lists($model = null, $p = 0){
        $model || $this->error('模型名标识必须！');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在！');

        $tablename = get_table_name($model['id']);
        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
        	if(trim($value) === ''){
        		continue;
        	}
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array	=	explode('|',$val);
                $fields[] = $array[0];
            }
        }
        
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        $map	=	array();
        $key	=	$model['search_key']?$model['search_key']:'title';
        if(isset($_REQUEST[$key])){
            $map[$key]	=	array('like','%'.$_GET[$key].'%');
            unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach($_REQUEST as $name=>$val){
            if(in_array($name,$fields)){
                $map[$name]	=	$val;
            }
        }
        $row    = empty($model['list_row']) ? 10 : $model['list_row'];

        //读取模型数据列表
        if($model['extend']){
            $name   = get_table_name($model['id']);
            $parent = get_table_name($model['extend']);
            $fix    = C("DB_PREFIX");

            $key = array_search('id', $fields);
            if(false === $key){
                array_push($fields, "{$fix}{$parent}.id as id");
            } else {
                $fields[$key] = "{$fix}{$parent}.id as id";
            }

            /* 查询记录数 */
            $count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
            $data   = M($parent)
                ->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order("{$fix}{$parent}.id DESC")
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

        } else {
            if($model['need_pk']){
                in_array('id', $fields) || array_push($fields, 'id');
            }
            $name = parse_name(get_table_name($model['id']), true);
            $data = M($name)
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order($model['need_pk']?'id DESC':'')
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

            /* 查询记录总数 */
            $count = M($name)->where($map)->count();
        }

        //分页
        if($count > $row){
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }

        $data   =   $this->parseDocumentList($data,$model['id']);
        //判断是否本地上传
        foreach ($data  as &$d){
            $local_path = $this->isLocal($tablename,$d);
            if (!empty($local_path)){
                $tablename == 'listitems' && $d['img'] = $local_path;
                $tablename == 'items' && $d['image'] = $local_path;
                $tablename == 'items' && $d['img'] = $local_path;
            }
        }
        $this->assign('model', $model);
        $this->assign('_count', $count);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->meta_title = $model['title'].'列表';
        $this->display($model['template_list']);
    }

    public function del($model = null, $ids=null){
        $model = M('Model')->find($model);
        $model || $this->error('模型不存在！');

        $ids = array_unique((array)I('ids',0));

        if ( empty($ids) ) {
            $this->error('请选择要操作的数据!');
        }

        $Model = M(get_table_name($model['id']));
        $map = array('id' => array('in', $ids) );
        if($Model->where($map)->delete()){
            $this->success('删除成功');
        } else {
            $this->error('删除失败！');
        }
    }

    /**
     * 设置一条或者多条数据的状态
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus($model = null){
        if ($model == null){
            $this->error('无模块名');
        }
        return parent::setStatus($model);
    }
    
    public function edit($model = null, $id = 0){
        //获取模型信息
        $model_id = $model;

        $model = M('Model')->find($model);
        $model || $this->error('模型不存在！');
        if ($model['name'] == 'listitems'){
            $category_items =  M('category_items')->field(['id','title'])->where(['status'=>1])->select();
            $select  = M('listitems')->where(['id'=>$id])->getfield('category');
            $this->assign('category_items',$category_items);
            $this->assign('select',$select);
        }
        if(IS_POST){                   
            $Model  =   D(parse_name(get_table_name($model['id']),1)); 
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && $Model->save()){
                $this->success('保存'.$model['title'].'成功！', U('edit?model='.$model_id.'&id='.$id));
            } else {
                $this->error($Model->getError());
            }
        } else {
            $fields     = get_model_attribute($model['id']);
            //获取数据
            $tablename = get_table_name($model['id']);
            $data       = M($tablename)->find($id);
            
            //判断是否本地上传
            $local_path = $this->isLocal($tablename,$data);
            //dump($local_path);exit;
            // if (empty($local_path)){
            //     //贴图库处理
            //     if (($tablename == 'items' || $tablename == 'listitems') && !img_exists($data['s_url'])){
            //         if ($tablename == 'listitems' && img_exists($data['img'])){
            //             $tietu_result = tietu($data['img']);
            //         }elseif ($tablename == 'items' && img_exists($data['image'])) {
            //             $tietu_result = tietu($data['image']);
            //         }

            //         $this->recordTietu($tablename,$tietu_result,$id);
            //     }
            // }else{
                // $tablename == 'listitems' && $data['img'] = $local_path;
                // $tablename == 'items' && $data['image'] = $local_path;
            // }
            if (!empty($local_path)){
                $tablename == 'listitems' && $data['img'] = $local_path;
                $tablename == 'items' && $data['image'] = $local_path;
            }
            
            $data || $this->error('数据不存在！');
            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->assign('data', $data);
            $this->meta_title = '编辑'.$model['title'];
            $this->display($model['template_edit']?$model['template_edit']:'');
        }
    }

    public function add($model = null){
        //获取模型信息
        $model = M('Model')->where(array('status' => 1))->find($model);
        $model || $this->error('模型不存在！');
        if(IS_POST){
            $Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && $Model->add()){
                $this->success('添加'.$model['title'].'成功！', U('lists?model='.$model['name']));
            } else {
                $this->error($Model->getError());
            }
        } else {
            if ($model['name'] == 'listitems'){
                $category_items =  M('category_items')->field(['id','title'])->where(['status'=>1])->select();
                $select  = I('category');
                $this->assign('category_items',$category_items);
                $this->assign('select',$select);
            }
            $fields = get_model_attribute($model['id']);

            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->meta_title = '新增'.$model['title'];
            $this->display($model['template_add']?$model['template_add']:'');
        }
    }

    protected function checkAttr($Model,$model_id){
        $fields     =   get_model_attribute($model_id,false);
        $validate   =   $auto   =   array();
        foreach($fields as $key=>$attr){
            if($attr['is_must']){// 必填字段
                $validate[]  =  array($attr['name'],'require',$attr['title'].'必须!');
            }
            // 自动验证规则
            if(!empty($attr['validate_rule'])) {
                $validate[]  =  array($attr['name'],$attr['validate_rule'],$attr['error_info']?$attr['error_info']:$attr['title'].'验证错误',0,$attr['validate_type'],$attr['validate_time']);
            }
            // 自动完成规则
            if(!empty($attr['auto_rule'])) {
                $auto[]  =  array($attr['name'],$attr['auto_rule'],$attr['auto_time'],$attr['auto_type']);
            }elseif('checkbox'==$attr['type']){ // 多选型
                $auto[] =   array($attr['name'],'arr2str',3,'function');
            }elseif('date' == $attr['type']){ // 日期型
                $auto[] =   array($attr['name'],'strtotime',3,'function');
            }elseif('datetime' == $attr['type']){ // 时间型
                $auto[] =   array($attr['name'],'strtotime',3,'function');
            }
        }
        return $Model->validate($validate)->auto($auto);
    }
    
    //公共管理
    public function manage($model = null, $p = 0){
        $model || $this->error('模型名标识必须！');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $status = I('status');
        
        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在！');
        if ($model['template_list'] == 'Su/kan_listitems' || $model['template_list'] == 'Su/kan_items'){
            $model['template_list'] = 'Su/manage_lists';
        }

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        if ($model['name'] == 'items'){
            $grids = array(
                "id:ID",
                "title:标题",
                "pc_displayorder:PC排序",
                "m_displayorder:移动排序",
                "pc_status:是否在PC显示",
                "m_status:是否在移动显示",
                "status:状态",
                'cat_code:关联相册',
                "id:操作:jumpitems([id])|查看,[EDIT]|操作,[DELETE]|删除",
            );
        }
        foreach ($grids as $k => &$value) {
            
            //记录不需要显示，但需要表单字段
//            if (strstr($value,':') === FALSE){
//                $out_list[] = $k;
//            }
            if(trim($value) === ''){
                    continue;
            }
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array	=	explode('|',$val);
                $fields[] = $array[0];
            }

        }

        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        $map	=	array();
        $key	=	$model['search_key']?$model['search_key']:'title';
        if(isset($_REQUEST[$key])){
            $map[$key]	=	array('like','%'.$_GET[$key].'%');
            unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach($_REQUEST as $name=>$val){
            if(in_array($name,$fields)){
                $map[$name]	=	$val;
            }
        }

        $row    = empty($model['list_row']) ? 10 : $model['list_row'];
        //读取模型数据列表
        if($model['extend']){
            $name   = get_table_name($model['id']);
            $parent = get_table_name($model['extend']);
            $fix    = C("DB_PREFIX");

            $key = array_search('id', $fields);
            if(false === $key){
                array_push($fields, "{$fix}{$parent}.id as id");
            } else {
                $fields[$key] = "{$fix}{$parent}.id as id";
            }

            /* 查询记录数 */
            $count = M($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
            $data   = M($parent)
                ->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order("{$fix}{$parent}.id DESC")
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

        } else {
            if($model['need_pk']){
                in_array('id', $fields) || array_push($fields, 'id');
            }
            $name = parse_name(get_table_name($model['id']), true);
            $data = M($name)
                /* 查询指定字段，不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order($model['need_pk']?'id DESC':'')
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

            /* 查询记录总数 */
            $count = M($name)->where($map)->count();
        }

        //分页
        if($count > $row){
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }
        //去除不需要显示，但需要表单字段
//        foreach ($out_list as $out){
//            unset($grids[$out]);
//        }

        $data   =   $this->parseDocumentList($data,$model['id']);
        $this->assign('model', $model);
        $this->assign('_count', $count);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->meta_title = $model['title'].'列表';
        $this->display($model['template_list']);

    }
    
    public function myManage($model = null, $p = 0){

        $model || $this->error('模型名标识必须！');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $status = I('status');
        $category = I('category');
        
        //获取模型信息
        $model = M('Model')->getByName($model);
        $grids = array(
            "id:ID",
            "title:标题",
            "createtime:发布时间",
            "pc_displayorder:PC排序",
            "m_displayorder:移动排序",
            "pc_status:是否PC显示",
            "m_status:是否移动显示",
            "status:状态",
            'id:操作:jumplist([id])|查看,jumpdetail([id])|查看图集,[EDIT]|编辑,[DELETE]|删除'
        );
        foreach ($grids as $k => &$value) {
            
            //记录不需要显示，但需要表单字段
//            if (strstr($value,':') === FALSE){
//                $out_list[] = $k;
//            }
            if(trim($value) === ''){
                    continue;
            }
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']	=	$val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array	=	explode('|',$val);
                $fields[] = $array[0];
            }

        }
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 关键字搜索
        $map	=	array();
        $key	=	$model['search_key']?$model['search_key']:'title';
        if(isset($_REQUEST[$key])){
            $map[$key]	=	array('like','%'.$_GET[$key].'%');
            unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach($_REQUEST as $name=>$val){
            if(in_array($name,$fields)){
                $map[$name]	=	$val;
            }
        } 
        if ($model['name'] == 'listitems' && $category > 0){
            $map['category'] = $category;
        }
        $row    = empty($model['list_row']) ? 10 : $model['list_row'];
        $name = parse_name(get_table_name($model['id']), true);
        $data = M($name)
            /* 查询指定字段，不指定则查询所有字段 */
            ->field(empty($fields) ? true : $fields)
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order('id DESC')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();
        
        /* 查询记录总数 */
        $count = M($name)->where($map)->count();


        //分页
        if($count > $row){
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }
//        //去除不需要显示，但需要表单字段
//        foreach ($out_list as $out){
//            unset($grids[$out]);
//        }

        $data   =   $this->parseDocumentList($data,$model['id']);
        $this->assign('model', $model);
        $this->assign('_count', $count);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->meta_title = $model['title'].'列表';
        $this->display('Su/manage_lists');

    }
    
    /*记录贴图库数据*/
    // private function recordTietu($table = null,$data = array(),$id=null){

    //     if (empty($table)){
    //         $this->error('缺少数据表');
    //     }
    //     if (empty($data)){
    //         $this->error('缺少返回数据');
    //     }
    //     if (empty($id)){
    //         $this->error('缺少id');
    //     }
    //     //记录错误
    //     if ($data['code']){
    //        Log::record('贴图库错误:'.$data['info'],'NOTIC'); 
    //     }else{
    //         $itmesModel = M($table);
    //         $itmesModel->s_url = $data['s_url'];
    //         $itmesModel->t_url = $data['t_url'];
    //         $itmesModel->width = $data['width'];
    //         $itmesModel->height = $data['height'];
    //         $result = $itmesModel->where('id='.$id)->save();
    //         if ( false === $result ){
    //             $this->error('更新失败！');
    //         }
    //     }
    // }
    
    /* 判断是否本地上传 */
    private  function isLocal($tablename = FALSE,$data = array()){
        
        $tablename == FALSE && $this->error('缺少表名'); 
        empty($data)  && $this->error('缺少数据'); 
        $local_path = '';
        if ($tablename == 'items' && is_numeric($data['image'])){
            $local_path = M('picture')->where(['id'=>$data['image']])->getfield('path');
        }elseif ($tablename == 'listitems' && is_numeric($data['img'])){
            $local_path = M('picture')->where(['id'=>$data['img']])->getfield('path');
        }
        return $local_path;
    }
    

    
    public function test(){
        set_time_limit(0); 
//        $t = getimagesize('http://img3.kanchao.com/uplodefiles/2015_bdproduct/12/30/22/92D4B886D4F3EFB9EA9765DDABF13B3A.jpg');
//        dump($t);
        $obj = M('items');
        $img_arr = $obj->field(['id','img','img_width'])->page(2, 15000)->select();
        foreach ($img_arr as $img){
            echo $img['id'].'---';
            if (empty($img['img_width'])){
                
                $t = getimagesize($img['img']);
                $obj->img_width =$t[0];
                $obj->img_height = $t[1];
                $obj->where('id='.$img['id'])->save();
            }
            
        }
    }
    

}
